package ViewModel;

import android.content.Context;
import android.os.Message;
import android.os.Process;
import Helper.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.administrator.drinkdevice.MainActivity;
import com.example.administrator.drinkdevice.R;

import org.json.JSONArray;
import org.json.JSONObject;

import Component.CustomViewPager;
import Const.PublicDefine;
import DataAccess.DeviceDataAccess;
import Interface.IAsynCallBackListener;
import Service.SysService;

public class PickTest_ViewModel extends Base_ViewModel {
    public TextBind pickTimeView = new TextBind("--");
    public TextBind smallTimeView = new TextBind("");
    public ImageView checkView;
    public TextBind timeClose = new TextBind("");

    private CustomViewPager viewPager;
    private MainActivity_ViewModel mainViewModel;
    private JSONObject pickDevice = null;
    private boolean checkState = false;
    private DeviceDataAccess deviceDataAccess;
    private Thread getDeviceStateThread;
    private boolean exitflag = false;


    public PickTest_ViewModel(Context ctx, CustomViewPager viewPager, MainActivity_ViewModel mainViewModel) {
        super(ctx);
        this.viewPager = viewPager;
        this.mainViewModel = mainViewModel;
    }

    public void Init() {
        try {
            pickTimeView.Text.set("--");
            smallTimeView.Text.set("");
            deviceDataAccess = new DeviceDataAccess(getBaseContext());

            checkView = ((MainActivity) getBaseContext()).findViewById(R.id.check);
            checkView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setCheck(!checkState);
                }
            });

            //设置默认变量
            setCheck(checkState);
            pickDevice = mainViewModel.pickDevice;


            //启动接杯测试
            int res = PublicDefine.colaReader.enter_getCup_setting(pickDevice.getString("deviceId"), 1);
            Log.write("colaReader", "启动接杯测试res: " + res);
            if (res == 0) {
                Log.write("colaReader", "启动线程");
                exitflag = false;
                getDeviceStateThread = new Thread(runnableUi);
                getDeviceStateThread.start();
            } else {
                alert("启动接杯测试失败[" + res + "]");
            }

        } catch (Exception e) {
            e.printStackTrace();
            alert(GetExceptionMsg(e));
        }
    }

    //返回按钮事件
    public void goBackClick(View view) {
        try {
            exitflag = true;
            StopAutoClose();
            viewPager.setCurrentItem(4);
            PublicDefine.colaReader.exit_getCup_setting(pickDevice.getString("deviceId"));
        } catch (Exception e){
            e.printStackTrace();
            alert(GetExceptionMsg(e));

        }
    }

    //设置单选框事件
    private void setCheck(boolean check) {
        checkState = check;
        smallTimeView.Enabled.set(checkState);
        if (checkState) {
            if (!pickTimeView.Text.get().equals("--")) {
                int pickTime = Integer.valueOf(pickTimeView.Text.get());
                int smallTime = (int) (pickTime * 0.9);
                smallTimeView.Text.set(smallTime + "");
            }
            checkView.setImageDrawable(getBaseContext().getResources().getDrawable(R.drawable.icon_check));
        } else {
            checkView.setImageDrawable(getBaseContext().getResources().getDrawable(R.drawable.icon_uncheck));
        }
        setDevicePickTime();
    }

    //保存商品接杯计时
    private void setDevicePickTime() {
        try {
            String pickTimeStr = pickTimeView.Text.get();
            if (pickTimeStr.equals("--")) {
                return;
            }
            JSONObject deviceInfo = deviceDataAccess.getById(pickDevice.getString("deviceId"));
            JSONArray goodsList = deviceInfo.getJSONArray("goodsList");
            for (int i = 0; i < goodsList.length(); i++) {
                JSONObject goodsInfo = goodsList.getJSONObject(i);
                if (goodsInfo.getInt("goodsId") == pickDevice.getInt("goodsId")) {
                    JSONObject pickTimeJson = new JSONObject();
                    int pickTime = Integer.valueOf(pickTimeStr);
                    pickTimeJson.put("big", pickTime);
                    if (checkState) {
                        int smallTime = (int) (pickTime * 0.9);
                        if (!smallTimeView.Text.get().equals("")) {
                            smallTime = Integer.valueOf(smallTimeView.Text.get());
                        }
                        pickTimeJson.put("small", smallTime);
                    }
                    goodsInfo.put("pickTime", pickTimeJson);
                    goodsList.put(i, goodsInfo);
                    break;
                }
            }
            deviceInfo.put("goodsList", goodsList);
            deviceDataAccess.setDevice(deviceInfo);
        } catch (Exception e) {
            e.printStackTrace();
            alert(GetExceptionMsg(e));
        }
    }


    //获取设备状态
    Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            int round = 30;
            while (!exitflag) {
                try {
                    timeClose.Text.set(round + "");
                    round--;
                    if (round == 0) {
                        exitflag = true;
                        goBackClick(null);
                        return;
                    }

                    int stateRes = PublicDefine.colaReader.getGivenSlaveDeviceStatus(pickDevice.getString("deviceId"));
                    Log.write("colaReader", "获取设备状态res: " + stateRes);
                    if (stateRes == 0) {
                        int setCupState = PublicDefine.colaReader.slave_DeviceInfo.getSet_Cup_State();
                        Log.write("colaReader", "接杯测试状态: " + setCupState);
                        if (setCupState == 0) {
                            Log.write("colaReader", "接杯时间: " + PublicDefine.colaReader.slave_DeviceInfo.getLittle_USED_TIME());
                            exitflag = true;
                            Message msg = new Message();
                            msg.obj = new IAsynCallBackListener() {
                                @Override
                                public void onFinish(Object sender, Object data) {

                                    int pickTime = PublicDefine.colaReader.slave_DeviceInfo.getLittle_USED_TIME();
                                    int smallTime = (int) (pickTime * 0.9);

                                    pickTimeView.Text.set(pickTime + "");
                                    smallTimeView.Text.set(smallTime + "");
                                    setDevicePickTime();
                                }

                                @Override
                                public void onError(Object sender, Exception e) {

                                }
                            };
                            mHandler.sendMessage(msg);
                            break;
                        } else {
                            Thread.sleep(1000);
                        }
                    } else {
                        Thread.sleep(1000);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    alert(GetExceptionMsg(e));
                }
            }
        }
    };
}

